import { useNotifyStore, useThemeChangeStore } from "@/store/index";
import { useThemeMetadataStore } from "@/store/index";
import fileSaver from "file-saver";
import JSZip from "jszip";
import JSZipUtils from "jszip-utils";
import { ExportUtils } from "./export";
/**
 * 处理下载相关方法
 * 1、下载完成时，不能捕获
 * @returns 
 */
export function DownloadThemeUtils() {
  // 获取主题变更相关
  const themeChange = useThemeChangeStore();
  // 获取主题变量变更
  const themeMetadata = useThemeMetadataStore();
  // 导出主题工具类方法
  const { exportThemeCSS } = ExportUtils();
  // 提示
  const notify = useNotifyStore();
  /**
   * 日期格式转换
   * @param millisecond 毫秒
   * @param template 模板(可选)
   * @example formatDate(new Date(), "YYYY-mm-dd HH:MM:SS") => 2021-11-02 09:39:59
   */
  const formatDate = (
    millisecond: string | number | Date,
    template = "YYYY-mm-dd HH:MM:SS"
  ): string => {
    let res = "";
    try {
      type dateFormatType = {
        "Y+": string; // 年
        "m+": string; // 月
        "d+": string; // 日
        "H+": string; // 时
        "M+": string; // 分
        "S+": string; // 秒
      };
      const date = new Date(millisecond);
      const opt: dateFormatType = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
      };
      template = template || "YYYY-mm-dd";
      const keys = Object.keys(opt);
      keys.forEach((k) => {
        let tKey = k as keyof dateFormatType;
        const ret = new RegExp("(" + tKey + ")").exec(template);
        if (ret) {
          template = template.replace(
            ret[1],
            ret[1].length === 1
              ? opt[tKey]
              : opt[tKey].padStart(ret[1].length, "0")
          );
        }
      });
      res = template;
    } catch (error) {
      console.warn("日期格式化报错", error);
    }
    return res;
  };

  const getFileNameWithoutExt = (
    nameSuffix: string,
    themeName = ""
  ): string => {
    let result = "";
    const suffix = nameSuffix ? "(" + nameSuffix + ")" : "";
    switch (themeName) {
      case "framework":
        result = `${themeName}.${themeChange.themeColor}${suffix}`;
        break;

      default:
        result = `${themeChange.themeName}.${themeChange.themeColor}.${themeChange.themeSize}${suffix}`;
        break;
    }
    return result;
  };
  /**
   * 下载Farris压缩包
   */
  function downloadFarrisZip(nameSuffix: string) {
    nameSuffix = nameSuffix || formatDate(new Date());
    const zip = new JSZip();
    const tfilePath = `./static/farris/${themeChange.themeColor}/${themeChange.themeSize}/`;
    const imgsFiles = ["table-norecords.png"];
    const fontsFiles = ["farrisicon.ttf", "farrisicon-extend.ttf"];
    /**
     * 汇总图片
     */
    const imgZip = zip.folder("imgs");
    imgsFiles.forEach((fileName) => {
      imgZip &&
        imgZip.file(
          fileName,
          JSZipUtils.getBinaryContent(tfilePath + "imgs/" + fileName)
        );
    });
    /**
     * 汇总字体文件
     */
    fontsFiles.forEach((fileName) => {
      zip.file(fileName, JSZipUtils.getBinaryContent(tfilePath + fileName));
    });
    const fileName = getFileNameWithoutExt(nameSuffix, "");
    /**
     * 汇总样式文件
     * 如果没有变化，直接读取资源的farris-all.css
     */
    if (themeMetadata.modifiedCollection.length === 0) {
      zip.file(
        "farris-all.css",
        JSZipUtils.getBinaryContent(tfilePath + "farris-all.css")
      );
    } else {
      zip.file(`farris-all.css`, exportThemeCSS(), { binary: false });
    }
    /**
     * 生成
     */
    zip.generateAsync({ type: "blob" }).then((content: any) => {
      fileSaver.saveAs(content, fileName + ".zip");
    });
  }
  /**
   * 下载框架压缩包
   * @param nameSuffix
   */
  function downloadFrameworkZip(nameSuffix: string) {
    nameSuffix = nameSuffix || formatDate(new Date());
    const zip = new JSZip();
    const tfilePath = `./static/framework/${themeChange.themeColor}/`;
    const fileName = getFileNameWithoutExt(nameSuffix, "framework");
    /**
     * 汇总样式文件
     * 如果没有变化，直接读取资源的farris-all.css
     */
    if (themeMetadata.modifiedCollection.length === 0) {
      zip.file(
        "gsp-cloud-web.css",
        JSZipUtils.getBinaryContent(tfilePath + "gsp-cloud-web.min.css")
      );
    } else {
      zip.file(`gsp-cloud-web.css`, exportThemeCSS("framework"), {
        binary: false
      });
    }
    /**
     * 生成
     */
    zip.generateAsync({ type: "blob" }).then((content: any) => {
      fileSaver.saveAs(content, fileName + ".zip");
    });
  }
  function downloadZip() {
    let nameSuffix = formatDate(new Date());
    downloadFarrisZip(nameSuffix);
    downloadFrameworkZip(nameSuffix);
  }
  const downloadZipByTye = (type = "") => {
    notify.updateType('info','下载中，请关注浏览器下载文件');
    switch (type) {
      case "farris":
        downloadFarrisZip("");
        break;
      case "framework":
        downloadFrameworkZip("");
        break;
      default:
        downloadZip();
    }
  };
  return { downloadZipByTye };
}
